package com.lizemin.controller;

import com.lizemin.entity.GreetingMessage;
import com.lizemin.entity.HelloMessage;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

@Controller
public class GreetingController {

    private final SimpMessagingTemplate messagingTemplate;

    public GreetingController(SimpMessagingTemplate messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }

    @MessageMapping("/hello")  // 类似于 @RequestMapping("/hello")
    @SendTo("/topic/greetings") // 将消息发送给指定的客户端
    public GreetingMessage greeting(HelloMessage message) {
        String name = message.getName() != null ? message.getName() : "Guest";
        return new GreetingMessage("Hello, " + name + "!");
    }

    /**
     * 定时向客户端发送消息
     */
    @Scheduled(fixedRate = 30, timeUnit = TimeUnit.SECONDS)
    public void sendPeriodicMessages() {
        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String content = "你好啊，我是服务器，当前时间为：" + currentTime;
        messagingTemplate.convertAndSend("/topic/time", new GreetingMessage(content));
    }


}    